<?php

    ##################################################
    #
    # Copyright (c) 2012 ABSoft.
    # Copyright 2012 Sonhb
    # Written and Designed by James Hunt
    # 
    #
    ##################################################

    class billingformextension {
        function name() { return exponent_lang_loadKey('subsystems/users/profileextensions/billingformextension.php', 'extension_name'); }
        function author() { return 'SonHB - ABSoft Viet Nam - http://absoft.vn'; }
        function description() { return exponent_lang_loadKey('subsystems/users/profileextensions/billingformextension.php', 'extension_description'); }

        /**
        * 
        * @param form $form
        * @param user $user
        */
        function modifyForm($form, $user) { 
            global $db;
            $i18n = exponent_lang_loadFile('subsystems/users/profileextensions/billingformextension.php');
            if (!isset($user->user_billing) || $user->user_billing == null) {
                $user->user_billing = billingformextension::_setDefaults();
            }

            $form->addScript('cc_check',PATH_RELATIVE.'subsystems/users/profileextensions/billingformextension/cc_check.js');
            $form->addScript('cc_validator',PATH_RELATIVE.'subsystems/users/profileextensions/billingformextension/jquery.creditCardValidator.js');

            $form->register(null, "", new htmlcontrol('<br><div class="textmodule"><div class="textmodule_title"><h3>' . $i18n['header'] . '</h3> </div> </div>'));

            // css for form + name on card + card number       
            $html=' 
            <link rel="stylesheet" href="'.PATH_RELATIVE.'subsystems/users/profileextensions/billingformextension/cc_check.css">
            <ul class="cards">
            <li class="visa">Visa</li>
            <li class="visa_electron">Visa Electron</li>
            <li class="mastercard">MasterCard</li>
            <li class="discover">Discover</li>
            </ul>
            <table border="0"> 
            <tbody>
            <tr>
            <td><div id="nameControl" class="text control "><label><span class="label">'.$i18n['name_on_card'].'</span></label></div></td>
            <td><div id="nameControl" class="text control "><label><span class="label">'.$i18n['card_num'].'</span></label></div></td>
            </tr>
            <tr>
            <input type="checkbox" name="use_add" value="1" id="use_add" onchange="use_address()" '.(($user->user_billing->use_add==1)?'checked':'').'> '.$i18n['use_same'].' <br>  <br>
            <td style="vertical-align: top;">
            <span class="control">
            <input type="text" size="11"  value="'.$user->user_billing->name_on_card.'" class="control text" name="name_on_card" style="width: 175px;">
            </span></td>
            <td style="vertical-align: top;">
            <span class="control">
                <label for="card_number" id="card_error" generated="true" class="error" style="">&nbsp;</label>
                <input type="text" size="12"  value="'.$user->user_billing->card_num.'" class="text" name="card_num" id="card_number" style="width: 180px;">
            </span>
            </td>
            </tr>



            </tbody>  </table>


            ';
            $form->register(null,"",new htmlcontrol($html));

            $card_user = $user->user_billing;

            $month='';
            $today = getdate();

            for($d=1;$d<=12;$d++)
            {

                $month.='<option value="'.$d.'"' ;
                if(intval($card_user->month_exp)==$d)  $month.=' selected'  ;
                $month.='>'.$d.'</option>';
            }

            for($d=$today['year']+1;$d<=$today['year']+20;$d++)
            {

                $year1.='<option value="'.$d.'"' ;
                if(intval($card_user->year_exp)==$d)  $year1.=' selected'  ;
                $year1.='>'.$d.'</option>';
            }

            $html_month='<select class="select valid" id="month_exp" name="month_exp" size="1"  style="width: 60px;">
            '.$month.'
            </select>' ;
            $html_year='<select class="select valid" id="year_exp" name="year_exp" size="1"  style="width: 80px;">
            '.$year1.'
            </select>' ;

            $html1=' <table border="0"> 
            <tbody>
            <tr>
            <td colspan="2" style="width: 80px;"><div id="nameControl" class="text control "><label><span class="label"  style="width: 180px;" >'.$i18n['month_date'].'</span></label></div></td>

            <td><div id="nameControl" class="text control "><label><span class="label"  style="width: 180px;">'.$i18n['secur_code'].'</span></label></div></td>

            </tr>
            <tr>

            <td style="vertical-align: top;">
            <span class="control">
            '.$html_month.'  </span></td>
            <td style="vertical-align: top;">
            <span class="control">
            '.$html_year.' </span>
            </td>
            <td style="vertical-align: top;">
            <span class="control">
            <input type="text" size="12"  value="'.$card_user->secur_code.'" class="text  " name="secur_code" style="width: 180px;" maxlength="3">
            </span>
            </tr> 
            </tbody>  </table> 
            ';

            $form->register(null,"",new htmlcontrol($html1));

            //$form->register('month_exp',$i18n['month_exp'],new dropdowncontrol($card_user->month_exp,$month,false));

            //$form->register('year_exp',$i18n['year_exp'],new dropdowncontrol($card_user->year_exp,$year,false));
            //$form->register("secur_code", $i18n["secur_code"], new textcontrol($card_user->secur_code, 10, false, 15));
            $country=$db->selectDropdown('billing_country','name');
            //country
            foreach($country as $value=>$caption)

            {

                $country1.='<option value="'.$caption.'"' ;
                if(intval($card_user->country_id)==$caption)  $country1.=' selected'  ;
                $country1.='>'.$caption.'</option>';
            }

            $html_ct='<select class="select valid" id="country_id" name="country_id" size="1"  style="width: 140px;">
            '.$country1.'
            </select>' ;  

            $html_ct1=' <table border="0"> 
            <tbody>
            <tr>
            <td><div id="nameControl" class="text control "><label><span class="label"  style="width: 180px;">'.$i18n['country_id'].'</span></label></div></td>
            <td><div id="nameControl" class="text control "><label><span class="label"  style="width: 180px;">'.$i18n['address'].'</span></label></div></td>
            </tr>
            <tr>

            <td style="vertical-align: top;">
            <span class="control">
            '.$html_ct.'  </span></td>
            <td style="vertical-align: top;">
            <span class="control">
            <input type="text" size="12"  value="'.$card_user->address.'" class="text  " name="billing_address" style="width: 180px;">
            </span>
            </td>
            </tr> 
            </tbody>  </table> 
            ';
            $form->register(null,"",new htmlcontrol($html_ct1));
            //------------------ 

            $html3=' 

            <table border="0"> 
            <tbody>
            <tr>
            <td><div id="nameControl" class="text control "><label><span class="label">'.$i18n['city'].'</span></label></div></td>
            <td><div id="nameControl" class="text control "><label><span class="label">'.$i18n['zipcode'].'</span></label></div></td>
            </tr>
            <tr>

            <td style="vertical-align: top;">
            <span class="control">
            <input type="text" size="11"  value="'.$card_user->city.'" class="control text " name="billing_city" style="width: 175px;">
            </span></td>
            <td style="vertical-align: top;">
            <span class="control">
            <input type="text" size="12"  value="'.$card_user->zipcode.'" class="number text  " name="zipcode" style="width: 180px;">
            </span>
            </td>
            </tr>

            </tbody>  </table>


            ';
            $form->register(null,"",new htmlcontrol($html3));

            if ($card_user->card_checked == 0)
            {
                $form->register(null,"",new htmlcontrol("<div class='card_notvalid' id='card_notify'>".$i18n['card_notvalid']."</div>"));
            }
            else
            {
                $form->register(null,"",new htmlcontrol("<div class='card_valid' id='card_notify'>".$i18n['card_valid']."</div>"));
            }

            return $form;
        }

        function saveProfile($values, $user, $is_new) {
            global $db;
            $db->delete("user_billingform", "uid=" . $user->id);

            $billing = null;
            $billing->uid = intval( $user->id );
            $billing->cardtype = $values['cardtype'];
            $billing->name_on_card = $values['name_on_card'];
            $billing->card_num = $values['card_num'];
            $billing->month_exp = $values['month_exp'];
            $billing->year_exp = $values['year_exp'];
            $billing->secur_code = $values['secur_code'];
            $billing->country_id = $values['country_id'];
            $billing->address = $values['billing_address'];
            $billing->city = $values['billing_city'];
            $billing->zipcode = $values['zipcode'];
            $billing->use_add = $values['use_add'];
            // check this card is valid or not
            
            $test_cart = billingformextension::validate_cc_number($values['card_num']);
            if ($test_cart === false) // wrong
            {
                $billing->card_checked = 0;
                $billing->cardtype = "";
            }
            else
            {
                $billing->card_checked = 1;
                $billing->cardtype = $test_cart;
            }
            
            if ($billing->name_on_card == "")
                $billing->card_checked = 0;
            
            $today = getdate();
            if ((intval($today['year']) == intval( $billing->year_exp)) 
               && (intval($today['month']) <= intval($billing->month_exp)))
            {
                $billing->card_checked = 0;
            }
            
            $db->insertObject($billing, "user_billingform");

            $user->user_billing = $billing;
            unset($user->user_billing->uid);
            return $user;
        }

        function getProfile($user) {
            global $db;
            if (!isset($user->id)) {
                $user->user_billing = settingsextension::_setDefaults();
            } else {
                $user->user_billing = $db->selectObject("user_billingform", "uid=" . $user->id);
            }
            return $user;
        }

        function cleanup($user) {
            global $db;
            $db->delete("user_billingform", "uid=" . $user->id);
        }

        function clear() {
            global $db;
            $db->delete("user_billingform");
        }

        function hasData() {
            global $db;
            return ($db->countObjects("user_billingform") != 0);
        }

        function _setDefaults() {

            $billing = null;  
            $billing->cardtype = 1;
            $billing->name_on_card = "";
            $billing->card_num = "";
            $billing->month_exp = 1;
            $billing->year_exp = 2012;
            $billing->secur_code ="";
            $billing->country_id = 184;
            $billing->address = "";
            $billing->city = "";
            $billing->zipcode = "";
            return $billing;
        }

        static function validate_cc_number($cc_number) {
            /* Validate; return value is card type if valid. */
            $false = false;
            $card_type = "";
            $card_regexes = array(
            "/^4\d{12}(\d\d\d){0,1}$/" => "visa",
            "/^5[12345]\d{14}$/"       => "mastercard",
            "/^3[47]\d{13}$/"          => "amex",
            "/^6011\d{12}$/"           => "discover",
            "/^30[012345]\d{11}$/"     => "diners",
            "/^3[68]\d{12}$/"          => "diners",
            );

            foreach ($card_regexes as $regex => $type) {
                if (preg_match($regex, $cc_number)) {
                    $card_type = $type;
                    break;
                }
            }

            if (!$card_type) {
                return $false;
            }

            /*  mod 10 checksum algorithm  */
            $revcode = strrev($cc_number);
            $checksum = 0; 

            for ($i = 0; $i < strlen($revcode); $i++) {
                $current_num = intval($revcode[$i]);  
                if($i & 1) {  /* Odd  position */
                    $current_num *= 2;
                }
                /* Split digits and add. */
                $checksum += $current_num % 10; if
                ($current_num >  9) {
                    $checksum += 1;
                }
            }

            if ($checksum % 10 == 0) {
                return $card_type;
            } else {
                return $false;
            }
        }

    }

?>